﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace Ice.Toolkit.Utility
{
    /// <summary>
    /// Xml序列化,返序列化
    /// </summary>
    public class XmlSerializer
    {
        /// <summary>
        /// 将对像序列化为XML字符串
        /// </summary>
        /// <param name="obj">对像</param>
        /// <returns>Xml String</returns>
        public static String ToXml(object obj)
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());

            using (MemoryStream ms = new MemoryStream())
            {
                serializer.Serialize(ms, obj);

                StringBuilder result = new StringBuilder();

                result.Append(Encoding.UTF8.GetString(ms.ToArray()));

                return result.ToString();
            }
        }
        /// <summary>
        /// 将XML字符串返序列化为对像
        /// </summary>
        /// <typeparam name="ReturnType">对像类型</typeparam>
        /// <param name="xml">String</param>
        /// <returns>Object</returns>
        public static ReturnType FormatXml<ReturnType>(string xml)
        {
            ReturnType rt;

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ReturnType));

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                rt = (ReturnType)serializer.Deserialize(ms);
            }

            return rt;
        }
        /// <summary>
        /// 将XML字符串返序列化为对像
        /// </summary>
        /// <typeparam name="ReturnType">对像类型</typeparam>
        /// <param name="uri">地址</param>
        /// <returns>Object</returns>
        public static ReturnType FormatXmlByPath<ReturnType>(string uri)
        {
            System.Xml.Linq.XElement xml = null;

            try
            {
                xml = System.Xml.Linq.XElement.Load(uri);
            }
            catch 
            {
                return default(ReturnType);
            }

            return FormatXml<ReturnType>(xml.ToString());
        }
    }
}
